/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/


#include <QMessageBox>
#include <QLabel>
#include <QtSerialPort/QSerialPort>

#include "connection_serial.h"
#include "dialog.h"
#include "linuxcontrol.h"
#include "settingsdialog.h"


CxConnection_serial::CxConnection_serial(Dialog *pdialog):CxConnection(pdialog)
{
    //! [1]
        m_serial = new QSerialPort(this);
    //! [1]
        m_settings = new SettingsDialog;

        connect(m_serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),
                this, &CxConnection_serial::handleError);

    //! [2]
        connect(m_serial, &QSerialPort::readyRead, this, &CxConnection_serial::readData);
    //! [2]
    //  connect(console, &Console::getData, this, &MainWindow::writeData);
        //cx
       // openSerialPort();
    //! [3]
}

//! [6]
void CxConnection_serial::writeData(const QByteArray &data)
{
    m_serial->write(data);
}
//! [6]

void CxConnection_serial::readData()
{
    if (m_state == P2Pconnection)
    { //need to change P2P from user List

        QByteArray data = m_serial->readAll();

        QString getdata ;//QString(data);

        QString strinsert=  getdata.fromLatin1(data.toStdString().c_str()); ;

        ShowLog(strinsert);

        //if(NULL==m_pattachconnect)
        //	m_pattachconnect->Write(data);
        return;
    }
    if (m_state == WaitingForGreeting)
    {
        if (!readProtocolHeader_s())
        {
            ShowLog("serial wrong conneting");

            return;
        }
        if (currentDataType != Greeting)
        {
            ShowLog("serial not valid connecting");

            return;
        }
        m_state = ReadingGreeting;
    }

    if (m_state == ReadingGreeting)
    {
        if (!hasEnoughData_s())
            return;

        buffer = Eread_s(numBytesForCurrentDataType);
        if (buffer.size() != numBytesForCurrentDataType)
        {
            return;
        }

//      m_greetingusername = m_psocket->peerAddress().toString() + ':'+ QString::number(m_psocket->peerPort());
        m_greetingusername = tr("serial");
        m_pdialog->ShowLog(this,tr("Greet:")+m_greetingusername);

        currentDataType = Undefined;
        numBytesForCurrentDataType = 0;

//        if (!m_psocket->isValid())
//        {
//            ShowLog("no valid connect");
//            m_psocket->abort();
//            return;
//        }
//        if(0==m_cos)//client
//        {
//            sendIPKEY();
//            if(m_pdialog->getloguse())
//                relogin();
//        }
//        else
        {//server
            ShowLog(tr("User:")+QString(buffer));
            m_user = QString(buffer).remove(' ');

        }
        buffer.clear();
        //m_pdialog->LoginUSER(this);//set user name in client Greet


        m_state = ReadyForUse;
       // emit readyForUse();
    }


    do {
        if (currentDataType == Undefined)
        {
            if (!readProtocolHeader_s())
            {
                m_icontinuefail = m_icontinuefail + 1;
                if(m_icontinuefail>3)
                {
                    m_icontinuefail = 0;
                    ShowLog("wrong connet comminication");
                    overconnect_s();
                }
                return;
            }
        }
        if (!hasEnoughData_s())
            return;
        processData();
    } while (m_serial->bytesAvailable() > 0);
}

//! [8]
void CxConnection_serial::handleError(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::ResourceError) {
        ShowLog(tr("Critical Error:")+m_serial->errorString());
        closeSerialPort();
    }
}

CxConnection_serial::~CxConnection_serial()
{
    delete m_settings;
    //delete ui;
}

//! [4]
void CxConnection_serial::openSerialPort()
{
    SettingsDialog::Settings p = m_settings->settings();
    m_serial->setPortName(p.name);
    m_serial->setBaudRate(p.baudRate);
    m_serial->setDataBits(p.dataBits);
    m_serial->setParity(p.parity);
    m_serial->setStopBits(p.stopBits);
    m_serial->setFlowControl(p.flowControl);
    if (m_serial->open(QIODevice::ReadWrite)) {
        //console->setEnabled(true);
        //console->setLocalEchoEnabled(p.localEchoEnabled);
        //ui->actionConnect->setEnabled(false);
        //ui->actionDisconnect->setEnabled(true);
        //ui->actionConfigure->setEnabled(false);
        ShowLog(tr("Connected to %1 : %2, %3, %4, %5, %6")
                          .arg(p.name).arg(p.stringBaudRate).arg(p.stringDataBits)
                          .arg(p.stringParity).arg(p.stringStopBits)
                          .arg(p.stringFlowControl));
    } else {
        ShowLog(tr("Error")+ m_serial->errorString());

        ShowLog(tr("Open error"));
    }
}
//! [4]

//! [5]
void CxConnection_serial::closeSerialPort()
{
    if (m_serial->isOpen())
        m_serial->close();
    //console->setEnabled(false);
    //ui->actionConnect->setEnabled(true);
    //ui->actionDisconnect->setEnabled(false);
    //ui->actionConfigure->setEnabled(true);
    //showStatusMessage(tr("Disconnected"));
}
//! [5]

int CxConnection_serial::readEnProtolBuffer_s(int maxSize)
{
    if (maxSize > MaxBufferSize)
        return 0;

    int numBytesBeforeRead = buffer.size();
    if (numBytesBeforeRead == MaxBufferSize)
    {
        //abort();
        return 0;
    }

    if (m_serial->bytesAvailable() > 0 && buffer.size() < maxSize)
    {
        buffer=Eread(16);
    }
    //////////////////////////////////////////////////////////////////////////
    QString Qshow = buffer;

    //m_pdialog->ClientTextEdit->clear();
    //m_pdialog->ClientTextEdit->insertPlainText(m_user +tr(":") +Qshow);
    //////////////////////////////////////////////////////////////////////////

    QStringList	alist  =  Qshow.split(QLatin1String(" "));

    int isize = alist.size();

    if(isize>=2)
    {
        ProtocolHeaderbuff = alist.at(0) ;
        ProtocolSizebuff = alist.at(1) ;
    }
    else
    {
        ProtocolHeaderbuff = tr("");
        ProtocolSizebuff = tr("");

    }


    return buffer.size() - numBytesBeforeRead;
}

int CxConnection_serial::dataLengthForCurrentEnDataType_s()
{
    int number = ProtocolSizebuff.toInt();
    int numberf = (number/16 + (number%16>0?1:0))*16;
    ProtocolSizebuff.clear();
    buffer.clear();
    return numberf;
}

bool CxConnection_serial::readProtocolHeader_s()
{
    int idatalen = readEnProtolBuffer_s();
    if (idatalen <= 0)
    {
        return false;
    }

    if (ProtocolHeaderbuff == "PING") {
        currentDataType = Ping;
    } else if (ProtocolHeaderbuff == "PONG") {
        currentDataType = Pong;
    } else if (ProtocolHeaderbuff == "LOGIN") {
        currentDataType = Login;
    } else if (ProtocolHeaderbuff == "MESSAGE") {
        currentDataType = PlainText;
    } else if (ProtocolHeaderbuff == "GREETING") {
        currentDataType = Greeting;
    } else if (ProtocolHeaderbuff == "FINF") {
        currentDataType = GFileINF;
    } else if (ProtocolHeaderbuff == "DATA") {
        currentDataType = CxData;
    } else if (ProtocolHeaderbuff == "NEXT") {
        currentDataType = CxNext;
    }  else if (ProtocolHeaderbuff == "COMM") {
        currentDataType = CxCommand;
    }  else if (ProtocolHeaderbuff == "SAVEF") {
        currentDataType = CxSaveFile;
    }  else if (ProtocolHeaderbuff == "LOGOK") {
        currentDataType = Logok;
    }  else {
        currentDataType = Undefined;

        m_settings->read(idatalen);

        buffer.clear();

        ProtocolHeaderbuff.clear();
        ShowLog("not valid head");

        return false;
    }

    buffer.clear();
    ProtocolHeaderbuff.clear();
    numBytesForCurrentDataType = dataLengthForCurrentEnDataType_s();
    return true;
}

bool CxConnection_serial::hasEnoughData_s()
{

    if (numBytesForCurrentDataType <= 0)
        numBytesForCurrentDataType = dataLengthForCurrentEnDataType();

    if (m_psocket->bytesAvailable() < numBytesForCurrentDataType
            || numBytesForCurrentDataType <= 0) {

        return false;
    }

    return true;
}

qint64 CxConnection_serial::Ewrite_s(const QByteArray &data)
{
    int isize = data.size();

    memcpy(pchar,data.data(),isize);
    int iesize = CxEncrypt(pchar,isize);
    QByteArray data1(pchar,iesize);
    isize = m_serial->write(data1);

    return isize;
}


QByteArray CxConnection_serial::Eread_s(qint64 maxlen)
{
    QByteArray data = m_serial->read(maxlen);
    int isize = data.size();
    memcpy(pchar,data.data(),isize);
    int iesize = CxDecrypt(pchar,isize);
    QByteArray data1(pchar,iesize) ;

    return data1;
}
void CxConnection_serial::overconnect_s()
{
    m_iuserclass = 0;
    pingTimer.stop();
    m_dutytimer.stop();
//	if(m_psocket!=NULL)
//		m_psocket->close();
//	m_pdialog->removeconnect(this);
//	ShowLog("DisConnect");
//	m_pdialog->ClientstartButton->setEnabled(true);

//	if(m_cos==0)
    m_reconnectTimer.start();
        //restartruntimer(this);

}
void  CxConnection_serial::removelnull_s(QByteArray &buffer)
{
    int icsize = buffer.size();
    for(int j=icsize-1;j>=0;j--)
    {
        if(buffer.at(j)!=' ')
        {
            icsize = j;
            goto NextRunX1_s;
        }
    }
NextRunX1_s:
    buffer = buffer.mid(0,icsize+1);
}

void CxConnection_serial::processData_s()
{
    buffer = Eread_s(numBytesForCurrentDataType);
    if (buffer.size() != numBytesForCurrentDataType)
    {
        ShowLog("data loss");
        return;
    }
    pongTime.restart();
    QString message;
    QByteArray data;
    QByteArray dataf;
    int icurnum ;
    switch (currentDataType)
    {
    case Login:
        removelnull_s(buffer);
        message = QString::fromUtf8(buffer) ;
        m_greetingusername = message.remove(" ");
        IsAdminist_s(m_greetingusername);
        break;
    case PlainText:
        message = QString::fromUtf8(buffer) ;
       // emit newMessage(m_greetingusername, message);
        if (!(m_greetingusername.isEmpty() || message.isEmpty()))
            ShowLog(tr("MSG:")+message);
        break;
    case Ping:
        sendPong_s();
        break;
    case Pong:

        break;
    case CxCommand:
        removelnull_s(buffer);
        message = QString::fromUtf8(buffer) ;
        CommandProcess(message);
        break;
    case CxData:
        m_nextdataTime.restart();
        //message = QString::fromUtf8(buffer) ;
        DataPieceProcess(buffer);
        break;
    case CxNext:
        removelnull(buffer);
        m_nextdataTime.restart();
        message = QString::fromUtf8(buffer) ;
        //message =  message.remove(" ");
        icurnum = message.toInt();
        //
        //ShowLog("Next: "+message);
        if (!(m_greetingusername.isEmpty()
        || message.isEmpty()))
        {
            if(icurnum==0)
                ShowLog("Next: "+message);
            else
            {
                m_pdialog->updateProgress(tr("Get"),icurnum,m_imaxlen);
            }
        }

        if(message.mid(0,6)=="resend")
        {
            ShowLog("Next Resend");
            g_section.lock();
            int icp = getnextsend();
            g_section.unlock();
            //ShowLog(tr("!!!Next %1").arg(icp));
            if(icp>=0)
            {
                sendOnePiece(icp,m_apiece->qsid);
                m_ipmcurnum = icp;
            }
            else
            {
                m_isendfinish_data = 1;
                //ShowLog(tr("Next End %1").arg(icurnum));
                int idatasize = m_datalist.size();
                if(idatasize>0)
                {
                    m_datalist.pop_front();
                    m_pdialog->removelist(0);
                }

            }
        }
        if(icurnum<m_imaxlen
        &&icurnum>=0)
        {
            //m_pdialog->g_mutex.lock();
            //m_pdialog->g_cond.wait(&m_pdialog->g_mutex);
            //m_pdialog->g_cond.wakeOne();
            //m_pdialog->g_mutex.unlock();
            g_section.lock();
            setsendfinish(icurnum);
            int icp = getnextsend();
            g_section.unlock();
            //ShowLog(tr("!!!Next %1").arg(icp));
            if(icp>=0)
            {
                sendOnePiece(icp,m_apiece->qsid);
                m_ipmcurnum = icp;
            }
            else
            {
                m_isendfinish_data = 1;
                //ShowLog(tr("Next End %1").arg(icurnum));
                int idatasize = m_datalist.size();
                if(idatasize>0)
                {
                    m_datalist.pop_front();
                    m_pdialog->removelist(0);
                }

            }
        }
        else
        {
            m_isendfinish_data = 1;
            //ShowLog(tr("Next End %1").arg(icurnum));
            int idatasize = m_datalist.size();
            if(idatasize>0)
            {
                m_datalist.pop_front();
                m_pdialog->removelist(0);
            }

        }
        break;
    case GFileINF:
        //savebuffer.clear();
        break;
    case CxSaveFile:
        break;
    case Logok:
        {
            m_pdialog->LoginOK();
        }
        break;
    default:
        break;
    }

    currentDataType = Undefined;
    numBytesForCurrentDataType = 0;
    buffer.clear();
}

int CxConnection_serial::IsAdminist_s(const QString &user)
{
    QString cxname = "cxvision2016";
    QDateTime now = QDateTime::currentDateTime();
    QString qmh = now.toString(QLatin1String("MM"));
    QString qdy = now.toString(QLatin1String("dd"));
    QString qadmin =  cxname + qmh + qdy + ipstring;
    QString struser = user;
    if(struser.remove(tr(" "))==qadmin.remove(tr(" ")))
    {
        m_iuserclass = 1;
        sendLogok_s();
    }
    return 1;
}
void CxConnection_serial::sendPong_s()
{
    QByteArray msg  =  RandSum().toUtf8();
    msg  = EnHeadFormat_s(msg);
    QByteArray data = "PONG " + QByteArray::number(msg.size()) + ' ' ;

    QByteArray dataf =  EnHeadFormatRand_s(data) + msg;
    Ewrite_s(dataf);
}
void CxConnection_serial::sendGreetingMessage_s()
{
    QByteArray greeting = m_greetingMessage.toUtf8();
    greeting = EnHeadFormat_s(greeting);
    QByteArray data = "GREETING " + QByteArray::number(greeting.size()) + ' ' ;
    QByteArray dataf =  EnHeadFormat_s(data)+ greeting;
    if (Ewrite_s(dataf) == dataf.size())
        isGreetingMessageSent = true;
}
bool CxConnection_serial::sendMessage_s(const QString &message)
{
    if (message.isEmpty())
        return false;
    QByteArray msg = message.toUtf8();
      msg = EnHeadFormat_s(msg);
    QByteArray data = "MESSAGE " + QByteArray::number(msg.size()) + ' ' ;
    QByteArray dataf =  EnHeadFormat_s(data) + msg ;
    return (Ewrite_s(dataf) == dataf.size());
}
bool CxConnection_serial::sendLogin_s(const QString &message)
{
    if (message.isEmpty())
        return false;
    QByteArray msg = message.toUtf8();
    msg = EnHeadFormat_s(msg);
    QByteArray data = "LOGIN " + QByteArray::number(msg.size()) + ' ' ;
    QByteArray dataf =  EnHeadFormat_s(data) + msg ;
    return (Ewrite_s(dataf) == dataf.size());

}
bool CxConnection_serial::sendLogok_s()
{
    QByteArray msg  =  RandSum().toUtf8();
    msg  = EnHeadFormat_s(msg);
    QByteArray data = "LOGOK " + QByteArray::number(msg.size()) + ' ' ;
    QByteArray dataf =  EnHeadFormatRand_s(data) + msg;
    return Ewrite_s(dataf) == dataf.size();
}
bool CxConnection_serial::sendCommand_s(const QString &message,const QString &stid)
{
    if (message.isEmpty())
        return false;

    QByteArray msg = (stid + message).toUtf8();
    msg = EnHeadFormat_s(msg);
    QByteArray data = "COMM " + QByteArray::number(msg.size()) + ' ' ;
    QByteArray dataf =  EnHeadFormat_s(data) + msg ;
    return (Ewrite_s(dataf) == dataf.size());
}
QByteArray CxConnection_serial::EnHeadFormatRand_s(QByteArray headmsg)
{
    int itotalsize = headmsg.size();

    int ilastsize = itotalsize%16;

    for(int j = ilastsize;j<16;j++)
    {
        headmsg += (char)rand();
    }
    return headmsg;
}
QByteArray CxConnection_serial::EnHeadFormat_s(QByteArray headmsg)
{
    int itotalsize = headmsg.size();

    int ilastsize = itotalsize%16;
    //if(i>=16)
    //	return;//abort();
    for(int j = ilastsize;j<16;j++)
    {
        headmsg += ' ';
    }
    return headmsg;
}
QByteArray CxConnection_serial::EnHeadFormat2_s(QByteArray headmsg)
{
    int itotalsize = headmsg.size();

    int ilastsize = itotalsize%16;

    for(int j = ilastsize;j<16;j++)
    {
        headmsg = ' '+headmsg;
    }
    return headmsg;
}
void CxConnection_serial::relogin_s()
{
    QString cxname = "cxvision2016";
    QDateTime now = QDateTime::currentDateTime();
    QString qmh = now.toString(QLatin1String("MM"));
    QString qdy = now.toString(QLatin1String("dd"));

    QString qadmin =  cxname + qmh + qdy + ipstring;

    sendLogin_s(qadmin);
}
void CxConnection_serial::CommandProcess_s(QString &qcomm)
{
    QString qstrdate = qcomm.mid(0,8);
    qcomm = qcomm.mid(8);
    QStringList	alist  =  qcomm.split(QLatin1String(" "));
    QString QScom;
    QString QSparm;
    QString QSparmall = qcomm;
    for(int i = 0;i<qcomm.size() ;i++)
    {
        QChar achar = qcomm.at(i);
        if(achar==' ')
        {
            QScom = qcomm.mid(0,i);
            QSparm = qcomm.mid(i+1);
            goto CPNEXT0;
        }
    }
CPNEXT0:
    if(QScom=="")
    {
        QScom = qcomm;
    }
    QString QSparm1;
    QString QSparm2;
    QString QSparm3;
    QString QSparm4;
    QString QSparm5;
    QString QSparm6;
    int isize = 0;
    {
        QStringList	alistparm  = QSparm.split(QLatin1String(","));
        isize = alistparm.size();
        if(isize>=2)
        {
            QSparm1 = alistparm.at(0);
            QSparm2 = alistparm.at(1);
            if(isize>=3)
            {
                QSparm3 = alistparm.at(2);
                if(isize>=4)
                {
                    QSparm4 = alistparm.at(3);
                    if(isize>=5)
                    {
                        QSparm5 = alistparm.at(4);
                    }
                }
            }
        }
        else
        {
            QSparm1 = QSparm;
        }
    }
    ShowLog(tr("TIME:")+qstrdate +tr(" ") +qcomm);
    if(QScom=="setkey")
    {
        QDateTime now = QDateTime::currentDateTime();
        QString qyear = now.toString(QLatin1String("yyyy"));
        QString qmh = now.toString(QLatin1String("MM"));
        QString qdy = now.toString(QLatin1String("dd"));
        int iy = qyear.toInt();
        int im = qmh.toInt();
        int id = qdy.toInt();
        ipstring = QSparm1+QSparm2+QSparm3+QSparm4+QSparm5;
        int ip1 =  QSparm1.toInt();
        int ip2 =  QSparm2.toInt();
        int ip3 =  QSparm3.toInt();
        int ip4 =  QSparm4.toInt();
        int iport =  QSparm5.toInt();
        SetKey(ip4,id,iport,ip4,
            id,im,iport,ip4,
            iport,id,iport,ip4,
            ip4,id,iport,ip4);
        pingTimer.start(PingInterval,this);
        pongTime.start();
        sendMessage("[connect Valid]");
        ShowLog(tr("[connect ok]"));
        return;
    }
    if(QScom=="sendfinish")
    {
        SendFinish_s(QSparm1,QSparm2,qstrdate);
        return;
    }
    if(QScom=="ircmsg")
    {
        return;
    }

    {
        {
            m_qsprecommand = qcomm;
        }

    }
}
void CxConnection_serial::DataPieceProcess_s(QByteArray &qcomm)
{
    QByteArray QSparm[6];
    int ibegin = 0;
    int iend = 0;
    int iqnum = 0;
    int inulnum = 0;
    int isize = qcomm.size();
    for(int i = 0;i<isize ;i++)
    {
        QChar achar = qcomm.at(i);
        if(achar!=' ')
        {
            inulnum = i;
            goto NEXTRUN0;
        }
    }
NEXTRUN0:
    ibegin = inulnum + 1;//'X'
//CRC
    QByteArray tmpget;
    tmpget[0] = qcomm.at(ibegin);
    tmpget[1] = qcomm.at(ibegin+1);
    QByteArray tmp  = gemfieldCRC_s(qcomm.mid(ibegin+2));//CRC[0]+ CRC[1]
    if(tmpget[0]!=tmp[0]
    ||tmpget[1]!=tmp[1])
    {
        ShowLog(tr("CRC Error Get:")+tmpget.toHex() + tr("I:")+tmp.toHex())  ;
        sendNextResend_s();
        return;
    }
    ibegin = inulnum+3;
    for(int i = inulnum+3;i<isize ;i++)
    {
        QChar achar = qcomm.at(i);
        if(achar==',')
        {
            QSparm[iqnum] = qcomm.mid(ibegin,i-ibegin);
            iqnum = iqnum +1;
            ibegin = i+1;
            if(iqnum>=5)
                goto NEXTRUN1;
        }
    }
NEXTRUN1:
    QSparm[5] = qcomm.mid(ibegin);
    //show
    int itolsize =QSparm[1].toInt();
    int ipsize = QSparm[2].toInt();
    int icp = QSparm[3].toInt();
    g_filesection.lock();
    m_pdialog->getonepiecefile(icp,ipsize,itolsize, QSparm[0],QSparm[4],QSparm[5]);
    m_imaxlen = itolsize/ipsize + (itolsize%ipsize>0?1:0);
    int igetnum = m_pdialog->getfinishnum(m_imaxlen);
    g_filesection.unlock();
    if(igetnum==1)
    {
        if (!(m_greetingusername.isEmpty() ))
            ShowLog("[Get]");
    }
    else
    {
        if (!(m_greetingusername.isEmpty() ))
        {
            m_pdialog->updateProgress(tr("Get"),igetnum,m_imaxlen);
        }
    }
    if(igetnum<m_imaxlen)
        sendNext_s(icp);//finish this piece
    else
    {
        sendNext_s(99999999);
        ShowLog(QString(QSparm[4]) +tr("[Data End]"));
        if(2!=m_pdialog->getfilefinish())
            m_pdialog->settransferover();
        else
            return;
        g_datafinishsection.lock();
        QByteArray igettype;
        QByteArray igetstring;
        for(int i = 0;i<QSparm[0].size() ;i++)
        {
            QChar achar = QSparm[0].at(i);
            if(achar=='_')
            {
                igettype = QSparm[0].mid(0,i);
                igetstring = QSparm[0].mid(i+1);
                goto NEXTRUN2;
            }
        }
NEXTRUN2:
        if(igettype=="file")
        {
            m_pdialog->Get_SaveFileSend(igetstring);
        }
        else if(igettype=="datefile")
        {
            QString strdate = QString(QSparm[4].toStdString().c_str());
            m_pdialog->ResetDateLoop(strdate,1);
            m_pdialog->SetSQLRecord(strdate);
            m_pdialog->ShowLog(this,tr("[datafile Finish]"));
            m_pdialog->Get_SaveDateFileSend(igetstring);
        }
        else if(igettype=="page")
        {
            m_pdialog->Get_ShowPageSend();
        }
        else if(igettype=="image")
        {
            QByteArray qbw;
            QByteArray qbh;
            QByteArray qbtype;
            int i_num = 0;
            int iprenum = 0;
            for(int i = 0;i<igetstring.size() ;i++)
            {
                QChar achar = igetstring.at(i);
                if(achar=='_')
                {
                    if(0==i_num)
                    {
                        qbw = igetstring.mid(iprenum,i-iprenum);
                        iprenum = i + 1;
                        i_num = i_num + 1;
                    }
                    else if(1==i_num)
                    {
                        qbh = igetstring.mid(iprenum,i-iprenum);
                        iprenum = i + 1;
                        i_num = i_num + 1;
                        goto NEXTRUN3;
                    }
                }
            }
            if(i_num<=1)
                qbh = igetstring.mid(iprenum);
NEXTRUN3:
            int iw =qbw.toInt();
            int ih =qbh.toInt();
            m_pdialog->Get_SaveImageSend(iw,ih);
        }
        else if(igettype=="imageframe")
        {
            QByteArray qbw;
            QByteArray qbh;
            QByteArray qbtype;
            int i_num = 0;
            int iprenum = 0;
            for(int i = 0;i<igetstring.size() ;i++)
            {
                QChar achar = igetstring.at(i);
                if(achar=='_')
                {
                    if(0==i_num)
                    {
                        qbw = igetstring.mid(iprenum,i-iprenum);
                        iprenum = i + 1;
                        i_num = i_num + 1;
                    }
                    else if(1==i_num)
                    {
                        qbh = igetstring.mid(iprenum,i-iprenum);
                        iprenum = i + 1;
                        i_num = i_num + 1;
                        goto NEXTRUN4;
                    }
                }
            }
            if(i_num<=1)
                qbh = igetstring.mid(iprenum);
NEXTRUN4:
            int iw =qbw.toInt();
            int ih =qbh.toInt();
            m_pdialog->Get_SaveImageFrameSend(iw,ih,igetstring);
        }
        else if(igettype=="list")
        {
             m_pdialog->Get_SaveListSend();
        }
        else if(igettype=="sql")
        {
             m_pdialog->Get_SqlSend(this);
        }
        else if(igettype=="sqlx")
        {
            m_pdialog->Get_SqlxSend(this);
            QString strdate = QSparm[4].toStdString().c_str();
            m_pdialog->ResetDateLoop(strdate,1);
            g_dutyfinishsection.lock();
            m_isendfinish_duty = 1;
            g_dutyfinishsection.unlock();
            m_pdialog->ShowLog(this,tr("[SqlFinish]"));
            if(m_dutylist.size()>0)
            {
                m_dutylist.pop_front();
                m_pdialog->removelist(0);
                if(m_dutylist.size()==0)
                    m_pdialog->clearlist();
            }
        }

        else if(igettype=="sqlf")
        {
            m_pdialog->Get_SaveDateFileSend(igetstring);
            QString strdate = QSparm[4].toStdString().c_str();
            m_pdialog->ResetDateLoop(strdate,1);
            g_dutyfinishsection.lock();
            m_isendfinish_duty = 1;
            g_dutyfinishsection.unlock();
            m_pdialog->ShowLog(this,tr("[Sqlf Finish]"));
            if(m_dutylist.size()>0)
            {
                m_dutylist.pop_front();
                m_pdialog->removelist(0);
                if(m_dutylist.size()==0)
                    m_pdialog->clearlist();
            }
        }
        else
        {
            m_pdialog->Get_SaveFileSend(igetstring);
        }
        m_pdialog->RemoveRecoT(QString(QSparm[4]));
        g_datafinishsection.unlock();
    }
}

void CxConnection_serial::SendFinish_s(const QString &qmsg1,
                                       const QString &qmsg2,
                                       const QString &qstrdate)
{
    if(qmsg1==tr("Duty"))
    {
        g_dutyfinishsection.lock();
        m_isendfinish_duty = 1;
        g_dutyfinishsection.unlock();
        ShowLog(tr("[DutyFinish:")+qmsg2+tr("]"));
        int idutyid = qmsg2.toInt();
        int idutysize = m_dutylist.size();
        int inum = 0;
        if(idutysize>0)
        {
            m_dutylist.pop_front();
        }
    }
}
bool CxConnection_serial::sendNextResend_s()
{
    QString message(tr("resend"));
    QByteArray msg = message.toUtf8();
    msg = EnHeadFormat_s(msg);
    QByteArray data = "NEXT " + QByteArray::number(msg.size()) + ' ' ;
    QByteArray dataf =  EnHeadFormat_s(data) + msg ;
    return (Ewrite_s(dataf) == dataf.size());
}

inline int CxConnection::sendpiecewaittime_s(int icp)
{
    int itimes = m_apiece->m_ipiecestatus[icp];
    if(itimes>=0)
    {
        QString qstime =  QDateTime::currentDateTime().toString(QLatin1String("ddhhmmss"));
        QString qsmstime = QTime::currentTime().toString("zzz");
        int icurtimeint = qstime.toInt()*1000+qsmstime.toInt();
        if(0==itimes)
        {
            m_apiece->m_ipiecestatus[icp] = icurtimeint;
            return 0;
        }
        else if(itimes>0)
        {
            int icurtimes = icurtimeint - itimes ;
            return icurtimes;
        }
    }
    else if(-1==itimes)
        return -1;

}
inline int CxConnection_serial::piececanbesend_s(int icp)//1 can be transfer, 0 no be transfer
{
    int ipasstime = sendpiecewaittime_s(icp);
    if(0== ipasstime)
    {
        return 1;
    }
    else if(ipasstime>=30000)//transfer over 30 s no finish to retransfer
    {
        return 1;
    }
    else if(ipasstime<0)
        return 0;
    else if(ipasstime>0)
        return 0;
}
void CxConnection_serial::setsendfinish_s(int icp)
{
    m_apiece->m_ipiecestatus[icp] = -1;
}
int CxConnection_serial::getnextsend_s()
{
    for(int i=0;i<m_apiece->m_ipiecesize;i++)
    {
        if(piececanbesend_s(i)>0)
        {
            return i;
        }
    }
    return -1;
}

inline QByteArray CxConnection_serial::gemfieldCRC_s(QByteArray gemfield)
{
    QByteArray temp;

    unsigned short crc = 0xffff;
    unsigned short a,j,k;
    for(a=0;a<gemfield.size();a++)
    {
        crc =crc ^ ( (int)gemfield.at(a)>=0 ?  gemfield.at(a) : (gemfield.at(a)+256) );
        for(j=0;j<8;j++)
        {
            k=crc & 01;
            crc = crc >> 1;
            if (k==0) continue;
            crc =crc ^ 0xA001;
        }
    }
    temp[1] = crc/256;
    temp[0] = crc%256;

    return temp;
}

bool CxConnection_serial::sendOnePiece_s(int ipiece,const QString &stid)
{
    if (m_pstrdata->isEmpty())
        return false;
    int icurpos = ipiece * m_apiece->pieceLength;
    m_apiece->icurpiece = ipiece;
    QByteArray qmsg = m_apiece->qsname.toLocal8Bit()  + tr(",").toLocal8Bit()
        + QByteArray(tr("%1").arg(m_apiece->totallength).toLocal8Bit() ) + tr(",").toLocal8Bit()
        + QByteArray(tr("%1").arg(m_apiece->pieceLength).toLocal8Bit() )+ tr(",").toLocal8Bit()
        + QByteArray(tr("%1").arg(ipiece).toLocal8Bit() )+ tr(",").toLocal8Bit()
        + QByteArray(stid.toLocal8Bit())+ tr(",").toLocal8Bit()
        + m_pstrdata->mid(icurpos,m_apiece->pieceLength) ;
    QByteArray tmp  = 'X' + gemfieldCRC_s(qmsg);//CRC
    qmsg = tmp + qmsg  ;
    QByteArray msg = EnHeadFormat2_s(qmsg);
    QByteArray data = "DATA " + QByteArray::number(msg.size()) + ' ' ;
    QByteArray dataf =  EnHeadFormat_s(data)+  msg ;
    return Ewrite_s(dataf) == dataf.size();
}
bool CxConnection_serial::sendNext_s(int ipiece)
{
    if (ipiece<0)
        return false;
    QString message(tr("%1").arg(ipiece));
    QByteArray msg = message.toUtf8();
    msg = EnHeadFormat_s(msg);
    QByteArray data = "NEXT " + QByteArray::number(msg.size()) + ' ' ;
    QByteArray dataf =  EnHeadFormat_s(data) + msg ;
    return (Ewrite_s(dataf) == dataf.size());
}
bool CxConnection_serial::sendNextResend_s()
{
    QString message(tr("resend"));
    QByteArray msg = message.toUtf8();
    msg = EnHeadFormat_s(msg);
    QByteArray data = "NEXT " + QByteArray::number(msg.size()) + ' ' ;
    QByteArray dataf =  EnHeadFormat_s(data) + msg ;
    return (Ewrite_s(dataf) == dataf.size());
}
bool CxConnection_serial::sendData_s(CxPiece * apiece)
{
    m_apiece = apiece;

    m_pstrdata = apiece->pstringbuf;

    if (m_pstrdata->isEmpty())
        return false;

    m_imaxlen =  apiece->totallength/apiece->pieceLength + (apiece->totallength%apiece->pieceLength>0?1:0);

    apiece->m_ipiecesize = m_imaxlen;

    g_section.lock();

    int icp = getnextsend();

    g_section.unlock();

    if(icp>=0)
    {
        sendOnePiece_s(icp,apiece->qsid);
        m_ipmcurnum = icp;
    }
    else
    {
        m_isendfinish_data = 1;
        ShowLog("Next End");
        int idatasize = m_datalist.size();
        if(idatasize>0)
        {
            m_datalist.pop_front();
            m_pdialog->removelist(0);
        }
    }
    return true;
}

void CxConnection_serial::timerEvent(QTimerEvent *timerEvent)
{
    if(timerEvent->timerId() == m_dutytimer.timerId())
    {
        m_dutytimer.stop();
        Run_s();
        m_dutytimer.start(20, this);
    }
    else if(timerEvent->timerId() == pingTimer.timerId())
    {
        if (pongTime.elapsed() > PongTimeout)
        {
            ShowLog("no ping DisConnect");
            overconnect_s();
            return;
        }

        QByteArray msg  =  RandSum().toUtf8();
        msg  = EnHeadFormat_s(msg);
        QByteArray data = "PING " + QByteArray::number(msg.size()) + ' ' ;

        QByteArray dataf =  EnHeadFormatRand_s(data)+ msg;
        Ewrite_s(dataf);

    }
}
void CxConnection_serial::overconnect_s()
{
    m_iuserclass = 0;
    pingTimer.stop();
    m_dutytimer.stop();
    ShowLog("S DisConnect");
    m_reconnectTimer.start();
}
void CxConnection_serial::processReadyRead_s()
{
    if (m_state == P2Pconnection)
    { //need to change P2P from user List
        QByteArray data = m_serial->read(m_serial->bytesAvailable());
        if(NULL==m_pattachconnect)
            overconnect_s();
        else
            m_pattachconnect->Write(data);
        return;
    }
    if (m_state == WaitingForGreeting)
    {
        if (!readProtocolHeader_s())
        {
            ShowLog("user wrong conneting");
            overconnect_s();
            return;
        }
        if (currentDataType != Greeting)
        {
            ShowLog("not valid user connecting");
            overconnect_s();
            return;
        }
        m_state = ReadingGreeting;
    }
    if (m_state == ReadingGreeting)
    {
        if (!hasEnoughData_s())
            return;
        buffer = Eread_s(numBytesForCurrentDataType);
        if (buffer.size() != numBytesForCurrentDataType)
        {
            return;
        }

        m_greetingusername = tr("serial");
        m_pdialog->ShowLog(this,tr("Greet:")+m_greetingusername);


        currentDataType = Undefined;
        numBytesForCurrentDataType = 0;


        ShowLog(tr("User:")+QString(buffer));
        m_user = QString(buffer).remove(' ');

        buffer.clear();
        //m_pdialog->LoginUSER(this);//set user name in client Greet

        m_state = ReadyForUse;
        //emit readyForUse();
    }


    do {
        if (currentDataType == Undefined)
        {
            if (!readProtocolHeader_s())
            {
                m_icontinuefail = m_icontinuefail + 1;
                if(m_icontinuefail>3)
                {
                    m_icontinuefail = 0;
                    ShowLog("wrong connet comminication");
                    overconnect_s();
                }
                return;
            }
        }
        if (!hasEnoughData_s())
            return;
        processData_s();
    } while (m_serial->bytesAvailable() > 0);
}
bool CxConnection_serial::WaitNextMsg_s(int iwaittime)
{
    if (m_nextdataTime.elapsed() > iwaittime)
    {
        return true;
    }
    return false;
}


void CxConnection_serial::Send_Data_s()
{
    m_apiece = m_datalist[0];
    sendData_s(m_apiece);
}
void CxConnection_serial::Run_s()
{
    if(m_serial->isReadable())
    {
        if(1==m_isendfinish_data
            &&1==m_isendfinish_duty)
        {
            int idatasize = m_datalist.size();
            if(idatasize>0)
            {
                m_isendfinish_data = 0;
                Send_Data_s();
                m_nextdataTime.restart();
                return;
            }
        }
        else if(0==m_isendfinish_data
            &&1==m_isendfinish_duty)
        {
            int idatasize = m_datalist.size();
            if(idatasize>0)
            {
                if( WaitNextMsg_s())
                {
                    m_isendfinish_data = 1;
                    m_pdialog->ShowLog(this,"Wait Next Data Over Time");
                    //resend
                    m_nextdataTime.restart();
                    m_datalist.pop_front();
                    return;
                }
            }
        }

        if(1==m_isendfinish_duty
            &&1==m_isendfinish_data)
        {
            int idutysize = m_dutylist.size();
            if(idutysize>0)
            {
                    switch(m_dutylist[0].m_itype)
                    {
                        case 0:
                            {
                                int its = 	QTime::currentTime().second();

                                int itm = 	QTime::currentTime().minute();

                                int ith = 	QTime::currentTime().hour();

                                QString qsdd= QDateTime::currentDateTime().toString(QLatin1String("dd"));

                                int itd = qsdd.toInt();

                                int inum = itd *1000000 +ith* 10000 + itm *100 + its;

                                qsdd =  qsdd + QTime::currentTime().toString(QLatin1String("hhmmss"));

                                if(inum>m_dutylist[0].m_stime.toInt()
                                    &&1!=m_dutylist[0].m_istats)
                                {
                                    m_dutylist[0].m_istats = 1;

                                    g_dutyfinishsection.lock();
                                    m_isendfinish_duty = 0;
                                    g_dutyfinishsection.unlock();
                                    {

                                        {
                                            if(m_dutylist[0].m_stcomm.mid(0,9)==tr("listclear"))
                                            {
                                                m_pdialog->Run_Clear();

                                                if(m_dutylist.size()>0)
                                                {
                                                    m_dutylist.pop_front();
                                                    m_pdialog->removelist(0);
                                                    if(m_dutylist.size()==0)
                                                        m_pdialog->clearlist();
                                                }
                                            }
                                            else if(m_dutylist[0].m_stcomm.mid(0,10)==tr("pageclass "))
                                            {
                                                QStringList alist = m_dutylist[0].m_stcomm.mid(10).split(",");
                                                if(alist.size()>1)
                                                {
                                                    QString qsp1,qsp2,qsp3,qsp4;
                                                    if(alist.size()>0)
                                                        qsp1 =alist[0];
                                                    if(alist.size()>1)
                                                        qsp2 =alist[1];
                                                    if(alist.size()>2)
                                                        qsp3 =alist[2];
                                                    if(alist.size()>3)
                                                        qsp4 =alist[3];

                                                    m_pdialog->Run_PageElementClassic(qsp1,qsp2,qsp3,qsp4);

                                                    if(m_dutylist.size()>0)
                                                    {
                                                        m_dutylist.pop_front();
                                                        m_pdialog->removelist(0);
                                                        if(m_dutylist.size()==0)
                                                            m_pdialog->clearlist();
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if(m_dutylist[0].m_stime.toInt()!=0)
                                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                                else
                                                    sendCommand(m_dutylist[0].m_stcomm,qsdd);
                                            }
                                        }

                                    }

                                    m_nextdataTime.restart();
                                    m_pdialog->setWindowTitle(QString::fromLatin1("CxVisionAImini V5.8 T:") + qsdd);
                                }
                                else if(inum>m_dutylist[0].m_stime.toInt()
                                    &&1==m_dutylist[0].m_istats)
                                {
                                    if(WaitNextMsg_s())
                                    {
                                        g_dutyfinishsection.lock();
                                        m_isendfinish_duty = 0;
                                        g_dutyfinishsection.unlock();
                                        {
                                            m_dutylist.pop_front();
                                            m_pdialog->removelist(0);
                                            if(m_dutylist.size()==0)
                                                m_pdialog->clearlist();
                                        }
                                        m_nextdataTime.restart();
                                        m_pdialog->setWindowTitle(QString::fromLatin1("CxVisionAImini V5.8 T:") + qsdd);
                                        return;
                                    }
                                }
                            }
                            break;


                        case 5:
                            {
                                if( 1!=m_dutylist[0].m_istats)
                                {
                                    m_dutylist[0].m_istats = 1;
                                    g_dutyfinishsection.lock();
                                    m_isendfinish_duty = 0;
                                    g_dutyfinishsection.unlock();
                                    {
                                        if(m_dutylist[0].m_stcomm.mid(0,9)==tr("listclear"))
                                        {
                                            m_pdialog->Run_Clear();

                                            if(m_dutylist.size()>0)
                                            {
                                                m_dutylist.pop_front();
                                                m_pdialog->removelist(0);
                                                if(m_dutylist.size()==0)
                                                    m_pdialog->clearlist();
                                            }
                                        }
                                        else if(m_dutylist[0].m_stcomm.mid(0,10)==tr("pageclass "))
                                        {
                                            QStringList alist = m_dutylist[0].m_stcomm.mid(10).split(",");
                                            if(alist.size()>1)
                                            {
                                                QString qsp1,qsp2,qsp3,qsp4;
                                                if(alist.size()>0)
                                                    qsp1 =alist[0];
                                                if(alist.size()>1)
                                                    qsp2 =alist[1];
                                                if(alist.size()>2)
                                                    qsp3 =alist[2];
                                                if(alist.size()>3)
                                                    qsp4 =alist[3];

                                                m_pdialog->Run_PageElementClassic(qsp1,qsp2,qsp3,qsp4);

                                                if(m_dutylist.size()>0)
                                                {
                                                    m_dutylist.pop_front();
                                                    m_pdialog->removelist(0);
                                                    if(m_dutylist.size()==0)
                                                        m_pdialog->clearlist();
                                                }
                                            }
                                        }
                                        else
                                        {
                                             sendCommand_s(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);

                                        }

                                    }

                                    m_nextdataTime.restart();
                                }
                                else if( 1==m_dutylist[0].m_istats)
                                {
                                    if(WaitNextMsg_s())
                                    {
                                        g_dutyfinishsection.lock();
                                        m_isendfinish_duty = 0;
                                        g_dutyfinishsection.unlock();
                                        {
                                            m_dutylist.pop_front();
                                            m_pdialog->removelist(0);
                                            if(m_dutylist.size()==0)
                                                m_pdialog->clearlist();
                                        }
                                        m_nextdataTime.restart();
                                        return;
                                    }
                                }
                            }
                            break;
                        case 2://finish signal
                            sendCommand_s(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                            if(m_dutylist.size()>0)
                            {
                                m_dutylist.pop_front();
                                m_pdialog->removelist(0);
                                if(m_dutylist.size()==0)
                                    m_pdialog->clearlist();
                            }
                            break;
                        case 3://finish signal
                            {

                                else if(m_dutylist[0].m_stname=="getpage")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                    m_pdialog->Send_Page_Multi(m_user,0,m_dutylist[0].m_stime);
                                }
                                else if(m_dutylist[0].m_stname=="getpic")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                    m_pdialog->Send_Picture_Multi(m_user,0,m_dutylist[0].m_stime);
                                }
                                else if(m_dutylist[0].m_stname=="getfile")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                    m_pdialog->SendLocalFile_Multi(m_user,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                                }
                                else if(m_dutylist[0].m_stname=="getdesktop")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                    m_pdialog->Send_Desktop_Multi( m_user,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                                }
                                else if(m_dutylist[0].m_stname=="getview")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                    m_pdialog->Send_View_Multi(m_user,m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                                }
                                else if(m_dutylist[0].m_stname=="setview")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                    m_pdialog->Set_FrameView(m_dutylist[0].m_stparm1.toInt(),m_dutylist[0].m_stparm2.toInt(),m_dutylist[0].m_stparm3.toInt());
                                }
                                else if(m_dutylist[0].m_stname=="getmsg")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                    m_pdialog->Send_MouseKeyBoardMsg_Multi(m_dutylist[0].m_stparm1,m_dutylist[0].m_stime);
                                }
                                else if(m_dutylist[0].m_stname=="getlist")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);

                                    if(m_dutylist[0].m_stparm2!=""
                                    ||m_dutylist[0].m_stparm2!=" ")
                                        m_pdialog->Send_PageList_Multi(m_user,m_dutylist[0].m_stparm1.toInt(),m_dutylist[0].m_stparm2,0,m_dutylist[0].m_stime);
                                    else
                                        m_pdialog->Send_PageList_Multi(m_user);
                                }
                                else if(m_dutylist[0].m_stname=="dir")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                    m_pdialog->FileDir(this,m_dutylist[0].m_stparm1);
                                }
                                else if(m_dutylist[0].m_stname=="psize")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                    setpiecesize(m_dutylist[0].m_stparm1.toInt());
                                }
                                else if(m_dutylist[0].m_stname=="ver")
                                {
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                    AddMsg("Ver171106");
                                }
                                else
                                {//unknow comm
                                    sendCommand(m_dutylist[0].m_stcomm,m_dutylist[0].m_stime);
                                }
                                if(m_dutylist.size()>0)
                                {
                                    m_dutylist.pop_front();
                                    m_pdialog->removelist(0);
                                    if(m_dutylist.size()==0)
                                        m_pdialog->clearlist();
                                }
                            }
                            break;
                        case 4://loacla signal
                        {

                        }
                        break;
                    }
               return;
            }
        }
        else if(1==m_isendfinish_data
            &&0==m_isendfinish_duty)
        {
            int idatasize = m_dutylist.size();
            if(idatasize>0)
            {
                    if(WaitNextMsg())
                    {
                        m_pdialog->ShowLog(this,"Wait Duty Over Time new connect");

                        g_dutyfinishsection.lock();
                        m_isendfinish_duty = 1;
                        g_dutyfinishsection.unlock();
                        {
                            //m_dutylist.pop_front();
                            //m_pdialog->removelist(0);
                            //if(m_dutylist.size()==0)
                            //	m_pdialog->clearlist();
                            m_nextdataTime.restart();
                        }
                        return;
                    }
            }
        }
        if(1==m_isendfinish_data)
        {
            int imsgsize = m_msglist.size();
            if(imsgsize>0)
            {
                sendMessage_s(m_msglist[0]);
                m_msglist.pop_front();
            }
        }
    }
}
void CxConnection_serial::AddMsg_s(const QString &qstring)
{
    m_msglist.push_back(qstring);
}
